package com.shouxin.attendance.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.webkit.URLUtil;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.shouxin.attendance.R;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 类描述:版本更新类
 */
public class VersionCheck implements Handler.Callback {

	private static final Logger logger = Logger.getLogger(VersionCheck.class);

    private static final int EOOOR = 100001;

    public Context mContext;

    private String currentTempFilePath = "";

    private String fileEx = "";

    private String fileNa = "";

    private String strURL = "";

    private String strmsg = "";

    private TextView mText;

    private Dialog mProgressDialog;

    private int downsize = 0;

    private int downTotalSize = 0;

    private ProgressBar mProgressBar;

    private boolean intrrupt = false;

    private Handler myHandler = new Handler(Looper.getMainLooper(), this);

    public VersionCheck(Context context, String strURL, String strmsg) {
        this.mContext = context;
        this.strURL = strURL;
        this.strmsg = strmsg;
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 1000:
                downTotalSize = msg.getData().getInt("totalsize");
                mProgressBar.setMax(downTotalSize);
                break;
            case 1001:
                updateNotify(msg);
                break;
            case 1002:
	            logger.debug("hanldre 1002");
	            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
                break;
            case EOOOR:
                Toast.makeText(mContext, "更新失败", Toast.LENGTH_SHORT).show();
            default:
                break;
        }
        return true;
    }

    private void initProgressBar() {
        mProgressDialog = new Dialog(mContext, R.style.CommonDialog);
        mProgressDialog.setContentView(R.layout.layout_download);

        mText = (TextView) mProgressDialog.findViewById(R.id.download_progress_value);
        mText.setText("      00KB/0000KB  ");
        mProgressBar = (ProgressBar) mProgressDialog.findViewById(R.id.progress_download);

        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
	            logger.debug("progressDialog  onCancel ");
	            interruptDown();
            }
        });
        mProgressDialog.show();
    }

    public void check(boolean isForce) {
        if (isForce) {
            showForceDialog();
        } else {
            showUpdateDialog();
        }
    }

    private void showForceDialog() {
        String showStr = strmsg.isEmpty() ? "您需要更新应用才能使用叮当，是否更新?" : strmsg;
        new AlertDialog.Builder(mContext).setTitle("提示").setMessage(showStr).setPositiveButton("更新", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                downloadTheFile(strURL);
            }
        }).setNegativeButton("退出", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                ((Activity) mContext).finish();
            }
        }).show();
    }

    private void showUpdateDialog() {
        String showMessage = strmsg.isEmpty() ? "发现新版本，是否更新？:" : strmsg;
        new AlertDialog.Builder(mContext).setTitle("提示").setMessage(showMessage).setPositiveButton("更新", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                downloadTheFile(strURL);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).show();
    }

    private void downloadTheFile(final String strPath) {
	    logger.debug("文件下载路径strPath:" + strPath);

        fileEx = "apk";
        // 文件名
        fileNa = "temp";
        try {
            initProgressBar();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        doDownloadTheFile(strPath);
                    } catch (Exception e) {
                        if (mProgressDialog != null && mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
	                    logger.debug(e.getMessage());
	                    myHandler.sendEmptyMessage(EOOOR);
                    }
                }
            }).start();
        } catch (Exception e) {
            myHandler.sendEmptyMessage(EOOOR);
            e.printStackTrace();
        }
    }

    public void interruptDown() {
        intrrupt = true;
    }

    /**
     * 文件下载
     *
     * @author Jeremy
     * @date
     */
    public void doDownloadTheFile(String strPath) throws Exception {
        if (!URLUtil.isNetworkUrl(strPath)) {
	        logger.debug("getDataSource() It's a wrong URL!");
        } else {
            URL myURL = new URL(strPath);
            URLConnection conn = myURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            Message msg = new Message();
            msg.what = 1000;
            msg.getData().putInt("totalsize", conn.getContentLength());
            myHandler.sendMessage(msg);
            if (is == null) {
                throw new RuntimeException("stream is null");
            }
            File myTempFile = new File(Environment.getExternalStorageDirectory(), fileNa + "." + fileEx);
            currentTempFilePath = myTempFile.getAbsolutePath();
            FileOutputStream fos = new FileOutputStream(myTempFile);
            byte buf[] = new byte[1024 * 8];
            do {
                if (intrrupt) {
	                logger.debug("doDownloadTheFile interrupt");
	                Message mesg = myHandler.obtainMessage();
                    mesg.what = 1002;
                    myHandler.sendMessage(mesg);
                    intrrupt = false;
                    return;
                }

	            logger.debug("doDownloadTheFile downLoading......");

                int numread = is.read(buf);
                downsize += numread;
                if (numread <= 0) {
                    break;
                }
                fos.write(buf, 0, numread);
                Message mesg = myHandler.obtainMessage();
                mesg.getData().putInt("downsize", downsize);
                mesg.what = 1001;
                myHandler.sendMessage(mesg);
            } while (true);
	        logger.debug("getDataSource() Download ok...");
	        openFile(myTempFile);
            try {
                is.close();
            } catch (Exception ex) {
	            logger.error("getDataSource() error: " + ex.getMessage());
            }
        }
    }

    /**
     * 通过文件名打开文件
     */
    private void openFile(File f) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);    //或FLAG_ACTIVITY_PREVIOUS_IS_TOP
        intent.setAction(Intent.ACTION_VIEW);

        String type = getMIMEType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        ((Activity) mContext).startActivityForResult(intent, 0);
    }

    public void delFile() {
	    logger.debug("The TempFile(" + currentTempFilePath + ") was deleted.");
	    File myFile = new File(currentTempFilePath);
        if (myFile.exists()) {
            myFile.delete();
        }
    }

    /**
     * 获取文件类型
     */
    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();

        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else {
            type = "*";
        }
        if (end.equals("apk")) {
        } else {
            type += "/*";
        }
        return type;
    }

    /**
     * 更新下载进度
     */
    private void updateNotify(Message msg) {
        int downsize = msg.getData().getInt("downsize");
        double downtotalsized = downTotalSize;
        int myprogress = (int) (((double) downsize / downtotalsized) * 100);
        String pro = myprogress + "%" + "      " + (downsize / 1024) + "KB/" + (downTotalSize / 1024) + "KB";
        mText.setText(pro);
        mProgressBar.setProgress(downsize);

    }
}
